package com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import cn.qqtheme.framework.picker.OptionPicker
import cn.qqtheme.framework.widget.WheelView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.LoftAllInfoResponse
import com.gexiaobao.pigeon.app.model.bean.ShedPigeonListResponse
import com.gexiaobao.pigeon.app.model.param.AddLoftAgentParams
import com.gexiaobao.pigeon.app.model.param.RingSnParams
import com.gexiaobao.pigeon.app.model.param.UpDateLoftPigeonParam
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.ActivityShedPigeonPairBinding
import com.gexiaobao.pigeon.ui.dialog.PairCountDownDialog
import com.gexiaobao.pigeon.ui.dialog.RxEtInputDialog
import com.gexiaobao.pigeon.viewmodel.ShedPigeonViewModel
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.listener.OnCompressSinglePicListener
import com.zs.easy.imgcompress.util.GBMBKBUtil
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils.debugInfo
import java.io.File
import java.util.Locale


/**
 * @Author      : hxw
 * @Date        : 2024/5/6 17:16
 * @Describe    : 公棚配对
 */
class ActivityShedPigeonPair : BaseActivity<ShedPigeonViewModel, ActivityShedPigeonPairBinding>() {

    private lateinit var picker: OptionPicker
    private var loftMemberList: ArrayList<LoftAllInfoResponse.LoftMember> = arrayListOf()
    private var loftAgentList: ArrayList<LoftAllInfoResponse.LoftAgent> = arrayListOf()
    private var loftFeatherColorList: ArrayList<LoftAllInfoResponse.LoftFeatherColor> = arrayListOf()
    private var loftDeviceList: ArrayList<LoftAllInfoResponse.LoftDevice> = arrayListOf()

    private var mPositionName = 0//记录选择的name的position
    private var mPositionAgent = 0//记录选择的代理人的positionf
    private var mPositionColor = 0//记录选择的羽色的position
    private var mPositionDevice = 0//记录选择的设备的position
    private var featherColorId = 0
    private var mAgentId = 0
    private var mSex = 0
    private var mEyePattern = 0
    private var mLiveIs = 0
    private lateinit var dialogTimer: PairCountDownDialog
    private var mPigeonId = 0
    private var mMemberId = 0
    private var mRingId = ""
    private var bodyPic: File? = null
    private lateinit var dialog: RxEtInputDialog

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.toolbar.initClose("修改赛鸽信息") {
            finish()
        }
        mPositionDevice = KvUtils.decodeInt("shedDevicePosition")!!

        mViewModel.getAddPigeonLoftAllInfoListByOrg()

        val id = intent.getIntExtra("pigeonId", 0)
        mViewModel.getLoftPigeonDetail(id.toString())

        mDatabind.rbPigeonPairNo.setOnCheckedChangeListener { _, b ->
            if (b) mSex = 1
        }

        mDatabind.rbPigeonPairMale.setOnCheckedChangeListener { _, b ->
            if (b) mSex = 3

        }
        mDatabind.rbPigeonPairFemale.setOnCheckedChangeListener { _, b ->
            if (b) mSex = 2
        }
        mDatabind.rbPigeonPairNoColor.setOnCheckedChangeListener { _, b ->
            if (b) mEyePattern = 1
        }

        mDatabind.rbPigeonPairYellow.setOnCheckedChangeListener { _, b ->
            if (b) mEyePattern = 2
        }

        mDatabind.rbPigeonPairSha.setOnCheckedChangeListener { _, b ->
            if (b) mEyePattern = 3
        }

        mDatabind.rbPigeonPairNiu.setOnCheckedChangeListener { _, b ->
            if (b) mEyePattern = 4
        }

        mDatabind.rbShedPigeonSurvival.setOnCheckedChangeListener { _, b ->
            if (b) mLiveIs = 0
        }

        mDatabind.rbShedPigeonDeath.setOnCheckedChangeListener { _, b ->
            if (b) mLiveIs = 1
        }

        mDatabind.etRemark.addTextChangedListener {
            if (it != null) {
                mDatabind.tvRemarkNumber.text = it.length.toString() + "/200"
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.tvShedReceivePigeonColor,
            mDatabind.ivShedReceivePigeonColor,
            mDatabind.ivShedPigeonPairName,
            mDatabind.tvScanPigeonClock,
            mDatabind.ivScanPigeonClock,
            mDatabind.tvChooseAgent,
            mDatabind.ivChooseAgent,
            mDatabind.tvShedPair,
            mDatabind.tvPigeonPairCommit,
            mDatabind.conPicBody,
            mDatabind.ivDeleteBodyPic,
            mDatabind.tvNewAgent
        ) {
            when (it) {
                mDatabind.tvNewAgent -> {
                    showNewAgentDialog()
                }

                mDatabind.ivDeleteBodyPic -> {
                    mDatabind.ivTestPic.setImageBitmap(null)
                    bodyPic = null
                    mDatabind.ivDeleteBodyPic.visibility = View.GONE
                }

                mDatabind.conPicBody -> {
                    selectBodyPic()
                }

                mDatabind.tvPigeonPairCommit -> {
                    commitPigeonInfo()
                }

                mDatabind.tvShedPair -> {
                    showCountDownDialog()
                }

                mDatabind.tvChooseAgent, mDatabind.ivChooseAgent -> {
                    pickerFunction("agent")
                }

                mDatabind.tvScanPigeonClock, mDatabind.ivScanPigeonClock -> {
                    pickerFunction("device")
                }

                mDatabind.ivShedPigeonPairName -> {
                    pickerFunction("name")
                }

                mDatabind.tvShedReceivePigeonColor, mDatabind.ivShedReceivePigeonColor -> {
                    pickerFunction("color")
                }
            }
        }
    }

    private fun showNewAgentDialog() {
        dialog = RxEtInputDialog(this)
        dialog.setSureListener {
            if (dialog.getAgentName().toString().isEmpty()) {
                showMessage("请填写代理人名称")
                return@setSureListener
            }
            showLoading(getString(R.string.loading))
            val param = AddLoftAgentParams(
                name = dialog.getAgentName(),
                address = dialog.getAgentAddress(),
                mobile = dialog.getAgentMobile()
            )
            mViewModel.addLoftAgent(param)
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun selectBodyPic() {
        val selectionModel: PictureSelectionModel = PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPreviewInterceptListener(PictureUtil.getPreviewInterceptListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isDirectReturnSingle(true)
            .isOpenClickSound(false)
            .isPreviewImage(false)
            .isMaxSelectEnabledMask(false)
            .setMaxSelectNum(1)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: ArrayList<LocalMedia>?) {
                if (!result.isNullOrEmpty()) {
                    mDatabind.ivDeleteBodyPic.visibility = View.VISIBLE
                    mDatabind.ivTestPic.setImageURI(Uri.parse("file://" + result[0].realPath))

                    /** 把单张图片压缩到1024k以内 同时像素不超过1500（宽、高都不大于1500） */
                    EasyImgCompress.withSinglePic(this@ActivityShedPigeonPair, result[0].realPath)
                        .maxPx(1500)
                        .maxSize(1024)
                        .enableLog(true)
                        .setOnCompressSinglePicListener(object : OnCompressSinglePicListener {
                            override fun onStart() {
                                debugInfo("onStart")
                            }

                            override fun onSuccess(file: File) {
                                bodyPic = file
                                debugInfo("onSuccess size = " + GBMBKBUtil.getSize(file.length()) + " getAbsolutePath= " + file.absolutePath)
                            }

                            override fun onError(error: String) {
                                debugInfo("onError error = $error")
                            }
                        }).start()
                }
            }

            override fun onCancel() {}
        })
    }

    private fun commitPigeonInfo() {
        val yearRingNum = mDatabind.layoutRingNumber.tvRingNumberYear.text.toString().trim()
        val areaRingNum = mDatabind.layoutRingNumber.tvRingNumberArea.text.toString().trim()
        val ringNum = mDatabind.layoutRingNumber.tvRingNumber.text.toString().trim()
        when {
            mDatabind.etShedPigeonPairName.text.toString().trim().isEmpty() -> showMessage("请输入或选择鸽主名称")
            yearRingNum.isEmpty() || yearRingNum.length != 4 -> showMessage("足环号年份不正确")
            areaRingNum.isEmpty() -> showMessage("足环号地区不正确")
            ringNum.isEmpty() -> showMessage("请填写正确足环号")
            else -> {
                mRingId = "$yearRingNum-$areaRingNum-$ringNum"
                val body = UpDateLoftPigeonParam(
                    id = mPigeonId,
                    memberId = mMemberId,
                    ringId = mRingId.uppercase(Locale.getDefault()),
                    ringSn = mDatabind.tvPigoenPairNum.text.toString().trim(),
                    featherColor = featherColorId,
                    featherColorId = featherColorId,
                    agentId = mAgentId,
                    sex = mSex,
                    eyePattern = mEyePattern,
                    liveIs = mLiveIs,
                    loftPic = bodyPic,
                    pigeonDesc = mDatabind.etRemark.text.toString().trim()
                )
                showLoading(getString(R.string.loading))
                mViewModel.upDateLoftPigeon(body)
            }
        }
    }

    private fun showCountDownDialog() {
        if (job != null) {
            job?.cancel()
        }
        toPairRingSn()
        dialogTimer = PairCountDownDialog(this)
        dialogTimer.setCanceledOnTouchOutside(false)
        dialogTimer.setFullScreenWidth()
        dialogTimer.show()
        //开启倒计时60s
        job = countDownCoroutines(20, {
            dialogTimer.setCountDownTime(it)
        }, {
            dialogTimer.dismiss()
            if (job != null) {
                job!!.cancel()
            }
        }, lifecycleScope)
    }

    private fun toPairRingSn() {
        val deviceCode = mDatabind.tvScanPigeonClock.text.toString().trim()
        if (deviceCode.isEmpty()) {
            showMessage("未选择扫描鸽钟")
            return
        }
        val body = RingSnParams(deviceCode)
        mViewModel.geyRingSn(body)
    }

    private fun pickerFunction(type: String) {
        val nameKey: ArrayList<String> = arrayListOf()
        val agentKey: ArrayList<String> = arrayListOf()
        val colorKey: ArrayList<String> = arrayListOf()
        val deviceKey: ArrayList<String> = arrayListOf()
        when (type) {
            "name" -> {
                if (loftMemberList.isNotEmpty()) {
                    for ((index, item) in loftMemberList.withIndex()) {
                        if (item.mobile.isNotEmpty() && item.shedNo.isNotEmpty()) {
                            nameKey.add(item.name + "-" + item.mobile + "-" + item.shedNo)
                        } else if (item.mobile.isEmpty() && item.shedNo.isNotEmpty()) {
                            nameKey.add(item.name + "-" + item.shedNo)
                        } else if (item.mobile.isNotEmpty() && item.shedNo.isEmpty()) {
                            nameKey.add(item.name + "-" + item.mobile)
                        } else {
                            nameKey.add(item.name)
                        }
                        if (item.name == mDatabind.etShedPigeonPairName.text.toString().trim()) {
                            mPositionName = index
                        }
                    }
                }
                picker = OptionPicker(this, nameKey)
            }

            "agent" -> {
                if (loftAgentList.isNotEmpty()) {
                    for ((index, item) in loftAgentList.withIndex()) {
                        if (item.address.isNotEmpty() && item.mobile.isNotEmpty()) {
                            agentKey.add(item.name + "-" + item.address + "-" + item.mobile)
                        } else if (item.address.isEmpty() && item.mobile.isNotEmpty()) {
                            agentKey.add(item.name + "-" + item.mobile)
                        } else if (item.address.isNotEmpty() && item.mobile.isEmpty()) {
                            agentKey.add(item.name + "-" + item.address)
                        } else {
                            agentKey.add(item.name)
                        }
                        if (item.id == mAgentId) {
                            mPositionAgent = index
                        }
                    }
                }
                picker = OptionPicker(this, agentKey)
            }

            "color" -> {
                if (loftFeatherColorList.isNotEmpty()) {
                    for (item in loftFeatherColorList) {
                        colorKey.add(item.featherColor)
                    }
                    for ((index, item) in loftFeatherColorList.withIndex()) {
                        if (item.id != 1 && item.id == featherColorId) {
                            mPositionColor = index
                            break
                        } else {
                            mPositionColor = 2
                        }
                    }
                }
                picker = OptionPicker(this, colorKey)
            }

            "device" -> {
                if (loftDeviceList.isNotEmpty()) {
                    for (item in loftDeviceList) {
                        deviceKey.add(item.imsi)
                    }
                }
                picker = OptionPicker(this, deviceKey)
            }
        }

        val params = picker.window.attributes
        params.width = this.windowManager?.defaultDisplay!!.width
        picker.setCanceledOnTouchOutside(true)
        picker.setDividerRatio(WheelView.DividerConfig.FILL)
        picker.setShadowColor(ContextCompat.getColor(this, R.color.bg_light_bllue), 40)
        picker.setCycleDisable(true)
        when (type) {
            "name" -> {
                picker.selectedIndex = mPositionName
                picker.setTitleText("请选择鸽主")
            }

            "agent" -> {
                picker.selectedIndex = mPositionAgent
                picker.setTitleText("请选择代理人")
            }

            "color" -> {
                picker.selectedIndex = mPositionColor
                picker.setTitleText("请选择羽色")
            }

            "device" -> {
                picker.selectedIndex = mPositionDevice
                picker.setTitleText("请选择设备")
            }
        }
        picker.setTitleTextColor(Color.BLACK)
        picker.setTitleTextSize(18)
        picker.setSubmitText("确认")
        picker.setSubmitTextSize(17)
        picker.setSubmitTextColor(ContextCompat.getColor(this, R.color.bg_light_bllue))//确定按钮文字颜色
        picker.setCancelText("取消")
        picker.setCancelTextSize(17)
        picker.setCancelTextColor(ContextCompat.getColor(this, R.color.bg_light_bllue))//取消按钮文字颜色
        picker.setTextSize(18)
        picker.setLineSpaceMultiplier(3.0F)
        picker.setUseWeight(true)
        picker.setOnOptionPickListener(object : OptionPicker.OnOptionPickListener() {
            override fun onOptionPicked(index: Int, item: String) {
                when (type) {
                    "name" -> {
                        mDatabind.etShedPigeonPairName.setText(item)
                        mPositionName = index
                        mMemberId = loftMemberList[index].id
                    }

                    "agent" -> {
                        mDatabind.tvChooseAgent.text = item
                        mPositionAgent = index
                        mAgentId = loftAgentList[index].id
                    }

                    "color" -> {
                        mDatabind.tvShedReceivePigeonColor.text = item
                        mPositionColor = index
                        featherColorId = loftFeatherColorList[index].id
                    }

                    "device" -> {
                        mDatabind.tvScanPigeonClock.text = item
                        mPositionDevice = index
                        KvUtils.encode("shedDevicePosition", mPositionDevice)
                    }
                }
            }
        })
        picker.show()
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取赛鸽详情（公棚） */
        mViewModel.shedPigeonDetailResult.observe(this) {
            if (it != null) {
                setDataUI(it)
                if (it.loftPicPath.isNotEmpty()) {
                    ImageLoaderManager.loadRoundImage(this, it.loftPicPath, mDatabind.ivTestPic, 10)
                }
            }
        }
        /** 新增代理人 */
        mViewModel.newAgentResult.observe(this) {
            mViewModel.getAddPigeonLoftAllInfoListByOrg()
            dismissLoading()
            dialog.dismiss()
        }
        /** 更新赛鸽信息（公棚） */
        mViewModel.upDateLoftPigeonResult.observe(this) {
            if (it.isSuccess) {
                setResult(Activity.RESULT_OK, Intent())
                finish()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 配对 */
        mViewModel.ringSn.observe(this) { result ->
            dialogTimer.dismiss()
            job?.cancel()
            parseState(result, {
                mDatabind.tvPigoenPairNum.text = it.ringSn
            }, {
                RxToast.showToast(it.msg)
            })
        }
        /** 获取工碰下所有下拉信息 */
        mViewModel.allInfoResult.observe(this) {
            if (it != null) {
                if (!it.isEmptyMember()) {
                    loftMemberList.clear()
                    loftMemberList.addAll(it.loftMemberList)
                }
                if (!it.isEmptyAgent()) {
                    loftAgentList.clear()
                    loftAgentList.addAll(it.loftAgentList)
                }
                if (!it.isEmptyFeatherColor()) {
                    loftFeatherColorList.clear()
                    loftFeatherColorList.addAll(it.loftFeatherColorList)
                }
                if (!it.isEmptyDevice()) {
                    mDatabind.tvScanPigeonClock.text = it.loftDeviceList[mPositionDevice].imsi
                    loftDeviceList.clear()
                    loftDeviceList.addAll(it.loftDeviceList)
                }
            }
        }
    }

    private fun setDataUI(data: ShedPigeonListResponse.ListData?) {
        mDatabind.data = data
        if (data != null) {
            mPigeonId = data.id
            mMemberId = data.memberId
            mRingId = data.ringId
            featherColorId = data.featherColorId
            mAgentId = data.agentId
            mSex = data.sex
            mEyePattern = data.eyePattern
            mLiveIs = data.liveIs
        }
        if (data != null) {
            if (data.ringId.isNotEmpty()) {
                val ringId = data.ringId.split("-")
                if (ringId.isNotEmpty() && ringId.size == 3) {
                    mDatabind.layoutRingNumber.tvRingNumberYear.setText(ringId[0])
                    mDatabind.layoutRingNumber.tvRingNumberArea.setText(ringId[1])
                    mDatabind.layoutRingNumber.tvRingNumber.setText(ringId[2])
                }
            }
            when (data.sex) {
                1 -> {
                    mDatabind.rbPigeonPairNo.isChecked = true
                }

                2 -> {
                    mDatabind.rbPigeonPairFemale.isChecked = true
                }

                3 -> {
                    mDatabind.rbPigeonPairMale.isChecked = true
                }
            }
            mViewModel.pigeonFeatherColor.set(data.featherColor)
            when (data.eyePattern) {
                1 -> {
                    mDatabind.rbPigeonPairNoColor.isChecked = true
                }

                2 -> {
                    mDatabind.rbPigeonPairYellow.isChecked = true
                }

                3 -> {
                    mDatabind.rbPigeonPairSha.isChecked = true
                }

                4 -> {
                    mDatabind.rbPigeonPairNiu.isChecked = true
                }
            }
            when (data.liveIs) {
                1 -> {
                    mDatabind.rbShedPigeonDeath.isChecked = true
                }

                0 -> {
                    mDatabind.rbShedPigeonSurvival.isChecked = true
                }
            }
        }
    }
}